package com.vitabuybuy.tv.ui.tencent.superplay

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.core.content.ContextCompat
import com.library.common.base.BaseFragment
import com.library.common.base.BaseViewModel
import com.library.common.toast.XToast
import com.library.common.util.SdCardUtil
import com.tencent.rtmp.ITXVodPlayListener
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.TXVodPlayConfig
import com.tencent.rtmp.TXVodPlayer
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.databinding.FragmentPlaybackBinding
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_playback.*
import kotlinx.android.synthetic.main.playback_control.*
import java.util.*
import kotlin.math.abs

class PlaybackFragment : BaseFragment<BaseViewModel, FragmentPlaybackBinding>(),
    ITXVodPlayListener {

    private var mTXVodPlayer: TXVodPlayer? = null // 点播播放器
    private lateinit var mTXConfig: TXVodPlayConfig // 点播配置
    private var mPlaying = false
    private var mVideoPause = false // 是否暂停 = false
    private var mCoverUrl: String? = null
    private var mPlayUrl: String? = null
    private var mTrackingTouchTS = 0L
    private var mStartSeek = false // 是否在
    private var curSeek: Int = 0
    var clickCallback: Consumer<Boolean>? = null
    var showFill = true
    var allShowControl = false
    var mRenderMode = TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN
    var mRenderRotation = -1
    private lateinit var mHandler: Handler

    override val layoutId: Int
        get() = R.layout.fragment_playback

    override fun initView(savedInstanceState: Bundle?) {
        mHandler = Handler()
        mTXVodPlayer = TXVodPlayer(activity)
        mTXConfig = TXVodPlayConfig()
        playback_layout.isEnabled = !allShowControl
        if (allShowControl) {
            playback_control_layout.visibility = View.VISIBLE
        } else {
            playback_control_layout.visibility = View.GONE
        }
        if (!showFill) {
            fill.visibility = View.GONE
        } else {
            fill.setOnClickListener {
                FillPlaybackActivity.openActivity(
                    mContext,
                    mCoverUrl,
                    mPlayUrl,
                    mSbProgress.progress
                )
            }
        }
        loadCover()
        if (mPlayUrl != null)
            startPlay()
    }

    override fun eventHandling() {
        mIvPlay.setOnClickListener {
            if (mPlaying) {
                if (mVideoPause) {
                    mTXVodPlayer?.resume()
                    mIvPlay.isSelected = true
                } else {
                    mTXVodPlayer?.pause()
                    mIvPlay.isSelected = false
                }
                mVideoPause = !mVideoPause
            } else {
                startPlay()
            }
        }
        mSbProgress.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, bFromUser: Boolean) {
                player_time.text = String.format(
                    Locale.CHINA,
                    "%02d:%02d:%02d",
                    progress / 3600,
                    progress % 3600 / 60,
                    progress % 60
                )
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                mStartSeek = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                mTXVodPlayer?.seek(seekBar.progress)
                mTrackingTouchTS = System.currentTimeMillis()
                mStartSeek = false
            }
        })
        playback_layout.setOnClickListener {
            if (mIvPlay.visibility == View.VISIBLE) {
                hideControl()
            } else {
                showControl()
            }
        }
    }


    /**
     * 显示播放控件
     */
    private fun showControl() {
        mIvPlay.visibility = View.VISIBLE
        mIvPlay.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.anim_alpha_in))
        playback_control_layout.visibility = View.VISIBLE
        playback_control_layout.startAnimation(
            AnimationUtils.loadAnimation(
                activity,
                R.anim.bottom_in
            )
        )
        clickCallback?.accept(true)
    }

    /**
     * 隐藏播放控件
     */
    private fun hideControl() {
        mIvPlay.visibility = View.GONE
        mIvPlay.startAnimation(
            AnimationUtils.loadAnimation(
                activity,
                R.anim.anim_alpha_out
            )
        )
        playback_control_layout.visibility = View.GONE
        playback_control_layout.startAnimation(
            AnimationUtils.loadAnimation(
                activity,
                R.anim.bottom_out
            )
        )
        clickCallback?.accept(false)
    }


    private fun startPlay() {
        mTXConfig.setCacheFolderPath(SdCardUtil.get(mContext).DEFAULT_VIDEO_PATH)
        mTXConfig.setMaxCacheItems(3)
        cover.visibility = View.VISIBLE//封面
        mTXVodPlayer?.run {
            this.setPlayerView(player)
            this.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT)
            this.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN)
            this.setVodListener(this@PlaybackFragment)
            this.setConfig(mTXConfig)
            this.setAutoPlay(true)
        }
        val result = mTXVodPlayer?.startPlay(mPlayUrl)
        if (0 != result) {
//            val rstData = Intent()
            if (-1 == result) {
                //"非腾讯云链接，若要放开限制请联系腾讯云商务团队"
            } else {
                //"视频流播放失败，Er  非腾讯云链接，若要放开限制请联系腾讯云商务团队
            }
            stopPlay(true)
//            finish()
        } else {
            mIvPlay.isSelected = true
            mPlaying = true
            if (!allShowControl) {
                mHandler.postDelayed({
                    hideControl()
                }, 2000L)
            } else {
                mIvPlay.visibility = View.GONE
            }
        }
    }

    private fun stopPlay(clearLastFrame: Boolean) {
        if (mTXVodPlayer != null) {
            mTXVodPlayer?.setVodListener(null)
            mTXVodPlayer?.stopPlay(clearLastFrame)
            mPlaying = false
            mHandler.removeMessages(0)
        }
    }

    override fun onResume() {
        super.onResume()
        if (!mVideoPause) {
            mTXVodPlayer?.resume()
        }
    }

    override fun onPause() {
        super.onPause()
        mTXVodPlayer?.pause()
    }

    override fun onDestroy() {
        stopPlay(true)
        mTXVodPlayer = null
        super.onDestroy()
    }

    fun setUrl(coverUrl: String?, replayAddress: String?, isStart: Boolean = true) {
        this.mCoverUrl = coverUrl
        if (cover != null)
            loadCover()
        mPlayUrl = replayAddress
        if (mTXVodPlayer != null && isStart)
            startPlay()
    }

    fun seek(seek: Int) {
        if (mTXVodPlayer != null)
            mTXVodPlayer?.seek(seek)
        this.curSeek = seek
    }

    fun getSeek(): Int {
        if (mSbProgress != null)
            return mSbProgress.progress
        return 0
    }

    override fun onPlayEvent(player: TXVodPlayer?, event: Int, param: Bundle?) {
        if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {
            if (mStartSeek) {
                return
            }
            val progress = param!!.getInt(TXLiveConstants.EVT_PLAY_PROGRESS)
            val duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION)
            val curTS = System.currentTimeMillis()
            // 避免滑动进度条松开的瞬间可能出现滑动条瞬间跳到上一个位置
            if (abs(curTS - mTrackingTouchTS) < 500) {
                return
            }
            mPlaying = true
            mTrackingTouchTS = curTS
            if (mSbProgress != null) {
                mSbProgress.progress = progress
            }
            if (video_time != null)
                video_time.text = String.format(
                    Locale.CHINA,
                    "%02d:%02d:%02d",
                    duration / 3600,
                    duration % 3600 / 60,
                    duration % 60
                )
            if (player_time != null)
                player_time.text = String.format(
                    Locale.CHINA,
                    "%02d:%02d:%02d",
                    progress / 3600,
                    progress % 3600 / 60,
                    progress % 60
                )

            if (mSbProgress != null) {
                mSbProgress.max = duration
            }
            if (curSeek > 0) {
                mTXVodPlayer?.seek(curSeek)
                curSeek = 0
            }
        } else if (event == TXLiveConstants.PLAY_ERR_NET_DISCONNECT) {
//            showErrorAndQuit("网络异常，请检查网络")
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
            stopPlay(false)
            mVideoPause = false
            if (video_time != null)
                video_time.text = "00:00:00"
            if (player_time != null)
                player_time.text = "00:00:00"
            if (mSbProgress != null)
                mSbProgress.progress = 0

            if (mIvPlay != null) {
                mIvPlay.isSelected = false
            }
            cover.visibility = View.VISIBLE
        } else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {
            cover.visibility = View.GONE
        } else if (event == TXLiveConstants.PLAY_WARNING_RECONNECT) {
            XToast.normal("视频无法播放，请检查播放地址是否正确")
        }
    }

    override fun onNetStatus(player: TXVodPlayer?, status: Bundle?) {
        if (mRenderRotation > -1) {
            mTXVodPlayer?.setRenderRotation(mRenderRotation)
        } else {
            status?.run {
                if (this.getInt(TXLiveConstants.NET_STATUS_VIDEO_WIDTH) > this.getInt(
                        TXLiveConstants.NET_STATUS_VIDEO_HEIGHT
                    )
                )
                    mTXVodPlayer?.setRenderRotation(TXLiveConstants.RENDER_ROTATION_LANDSCAPE)
                else
                    mTXVodPlayer?.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0x11 && resultCode == 100 && data != null) {
            val seek = data.getIntExtra("seek", 0)
            if (seek > 0)
                mTXVodPlayer?.seek(seek)
        }
    }

    /**
     * 加载封面
     */
    private fun loadCover() {
        if (mCoverUrl != null)
            ImageAdapter.setNomalImageUrl(
                cover,
                mCoverUrl,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
    }
}